package com.infore.remoteControl.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.infore.remoteControl.constant.Constants;
import com.infore.remoteControl.enums.ResultStatus;
import com.infore.remoteControl.service.IFileService;
import com.infore.remoteControl.util.ResultEntity;

@Service
public class FileServiceImpl implements IFileService {
	
	@Value("${filePath}")
    private String filePath; //文件下载配置路径
	
	@Override
	public void download(String fileUrl, boolean isOnLine, HttpServletResponse response) {
		String fileName = fileUrl;
		fileUrl = filePath + fileUrl;
		if (fileUrl == null || "".equals(fileUrl)) {
			return;
		}
		File f = new File(fileUrl);
		BufferedInputStream br = null;
		OutputStream out = null;
		try {
	        if (!f.exists()) {
	            response.sendError(404, "File not found!");
	            return;
	        }
	        br = new BufferedInputStream(new FileInputStream(f));
	        byte[] buf = new byte[1024];
	        int len = 0;
	        response.reset(); // 非常重要
	        fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
//	        fileName = FileUtil.resolveStr(fileName); 
//	        fileName = fileUrl.substring(fileUrl.lastIndexOf("\\") + 1, fileUrl.lastIndexOf("."));
	        if (isOnLine) { // 在线打开方式
	            URL u = new URL("file:///" + fileUrl);
	            response.setContentType(u.openConnection().getContentType());
	            response.setHeader("Content-Disposition", "inline; filename=" + fileName);
	            // 文件名应该编码成UTF-8
	        } else { // 纯下载方式
	            response.setContentType("application/x-msdownload");
	            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes()));
	        }
	        out = new BufferedOutputStream(response.getOutputStream());
	        while ((len = br.read(buf)) > 0) {
	            out.write(buf, 0, len);
	        }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public ResultEntity uploadFile(MultipartFile file, boolean isPath) {
		String path = filePath + file.getOriginalFilename();
		File newFile = new File(path);
		// 通过CommonsMultipartFile的方法直接写文件
		try {
			file.transferTo(newFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (isPath) {
			return new ResultEntity(ResultStatus.SUCCESS, Constants.FILE_SUCCESS).setInfo(path);
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.FILE_SUCCESS);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public ResultEntity upload(HttpServletRequest request) {
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				
				if (file != null) {
					String path = filePath + file.getOriginalFilename();
					// 上传
					try {
						file.transferTo(new File(path));
					} catch (IllegalStateException | IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return new ResultEntity(ResultStatus.SUCCESS, Constants.FILE_SUCCESS);
	}

	@Override
	public ResultEntity deleteFile(String filePath) {
		File file = new File(filePath);
		if (file.exists() && file.isFile()) {
			file.delete();
			return new ResultEntity(ResultStatus.SUCCESS, Constants.DELETE_SUCCESS);
		}
		return new ResultEntity(ResultStatus.ERROR, Constants.DELETE_FAILUE);
	}
	
}
